package com.geekstudy.rpc.tool.client;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.util.LinkedHashMap;
import java.util.Map;

public class RPCClientTool {


    public Map<String, String> invoke(String serverUrl, String className, String methodName, Map<String, String> paramMap) {
        Map<String, String> resultMap = new LinkedHashMap<String, String>();

        String paramString = "className=" + className + "&methodName=" + methodName;
        if(paramMap != null && paramMap.size() > 0) {
            for(String paramName : paramMap.keySet()) {
                paramString += "&" + paramName + "=" + paramMap.get(paramName);
            }
        }
        String fullUrl = serverUrl + "?" + paramString;
        String response = get(fullUrl);
        resultMap.put("requestUrl", fullUrl);
        resultMap.put("response", response);

        return resultMap;
    }

    public String get(String url) {
        String response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);


        } catch(Exception e) {
            System.out.println("HttpClientTool exception");
            e.printStackTrace();
        }
        return response;
    }
}
